<?php
if (!defined('__COLA_DIR__')) exit;

/**
 * 相关内容组件(根据标签关联)
 *
 * @author edikud
 * @package Widget
 * @copyright Copyright (c) 2019 Cola (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class Widget_Contents_Related extends Widget_Abstract_Contents
{

    /**
     * 执行函数,初始化数据
     *
     * @access public
     * @return void
     */
    public function execute()
    {
        $this->parameter->setDefault('limit=5');
		$tags = $this->parameter->tags;

        if ($tags) {
		    $cids = $this->db->select('table.relate.cid')
			->from('table.relate')
		    ->where('table.relate.mid = ?', array_rand($tags))
		    ->limit($this->parameter->limit + 1)
		    ->fetchAll();

            $cids = array_column($cids, 'cid');
            $key = array_search($this->parameter->cid, $cids);
            if($key !== false){  
                unset($cids[$key]);  
            } else {
		        array_pop($cids);
	        }

		    if($cids){
				$this->select()
				->where('table.contents.type = ?', $this->parameter->type)
				->where('table.contents.cid IN ('.substr( str_repeat( '?,', count( $cids ) ), 0, - 1 ).')', $cids)
			    ->fetchAll(array($this, 'push'));
		    }
        }
    }
}
